package com.ym.b2b.product.service.impl;

import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.ym.b2b.product.dao.*;
import com.ym.b2b.product.sqlbean.*;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.ym.b2b.commons.exception.BaseException;
import com.ym.b2b.commons.service.BaseService;
import com.ym.b2b.product.service.ProductService;
import com.zc.commons.base.Page;
import com.zc.commons.base.Result;
import com.zc.commons.util.ZcStringUtil;

@Service("productService")
public class ProductServiceImpl extends BaseService implements ProductService {

    private Logger                    logger = Logger.getLogger(getClass());
    @Autowired
    private ProductDao                productDao;

    @Autowired
    private EmBProductIntroductionDAO emBProductIntroductionDAO;

    @Autowired
    private EmBProductPictureDAO      emBProductPictureDAO;

    @Autowired
    private EmBProductTypeDAO         emBProductTypeDAO;

    @Autowired
    private EmBProductPaperBatchDAO   emBProductPaperBatchDAO;

    @Autowired
    private EmBProductPriceDao        emBProductPriceDao;

    @Autowired
    private EmBProductPromoDAO        emBProductPromoDAO;

    private Logger                    dbLog  = Logger.getLogger("db");

    @Override
    public Result searchPageProduct(EmBProduct emBProduct, Page<EmBProduct> page) {
        Result result = new Result();
        try {
            // 页码最低为1
            if (page.getPage() <= 1) {
                page.setPage(1);
            }
            // 获取分类中文名
            if (ZcStringUtil.isNotBlank(emBProduct.getProductTypeCode())) {
                EmBProductType t = new EmBProductType();
                t.setProductTypeCode(emBProduct.getProductTypeCode());
                t = emBProductTypeDAO.showEmBProductTypeDetail(t);
                if (null != t) {
                    emBProduct.setProductTypeName(t.getProductTypeName());
                }
            }
            result.setResultPage(productDao.searchPageProduct(emBProduct, page));
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new BaseException(Result.CODE_100, "查询异常");
        }
        return result;
    }

    @Override
    public Result showProductDetail(EmBProduct serchPro) throws BaseException {

        Result result = new Result();
        try {
            if (ZcStringUtil.isEmpty(serchPro.getProductCode())) {
                result.setCodeResult(Result.CODE_100, "编号的商品  为空!");
                return result;
            }
            EmBProduct emBProduct = productDao.showProductDetail(serchPro);

            if (emBProduct == null) {
                result.setCodeResult(Result.CODE_100, "这个编号的商品  不存在!");
                return result;
            }
            // 商品说明书
            EmBProductIntroduction EmBProductIntroduction = emBProductIntroductionDAO.showEmBProductIntroductionDetail(serchPro.getProductCode());
            if (null == EmBProductIntroduction) EmBProductIntroduction = new EmBProductIntroduction();

            // 商品图片
            EmBProductPicture emBProductPicture = new EmBProductPicture();
            emBProductPicture.setProductCode(serchPro.getProductCode());
            List<EmBProductPicture> pictureList = emBProductPictureDAO.searchEmBProductPicture(emBProductPicture);

            // 促销信息
            EmBProductPromo emBProductPromo = new EmBProductPromo();
            emBProductPromo.setProductCode(serchPro.getProductCode());
            emBProductPromo.setValid("true");
            EmBProductPromo promoDetail = emBProductPromoDAO.searchEmBProductPromo(emBProductPromo);
            // 是否在 我的搜藏里面
            Integer isExistFavo = productDao.isInFavolite(serchPro.getProductCode());
            emBProduct.setIsFavorite(isExistFavo);

            result.putData("pictureList", pictureList);
            result.putData("emBProduct", emBProduct);
            result.putData("emBProductIntroduction", EmBProductIntroduction);
            result.putData("promoDetail", promoDetail);

            // 浏览次数+1
            EmBProduct emBProduct1 = new EmBProduct();
            emBProduct1.setProductCode(emBProduct.getProductCode());
            emBProduct1.setUpdateDate(new Date());
            emBProduct1.setBrowseQuantity(1);
            productDao.updateEmBProduct(emBProduct1);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new BaseException(Result.CODE_100, "必填参数为空  或参数不合法 !");
        }
        return result;
    }

    @Override
    public Result searchAjaxProductList(EmBProduct emBProduct) throws BaseException {
        checkSearchType(emBProduct);

        // productDao.searchPageProduct(emBProduct, page));
        return null;
    }

    /**
     * @Title: checkSearchType
     * @Description: 对传入对象 进行类型归类
     */
    private void checkSearchType(EmBProduct emBProduct) {

        if (ZcStringUtil.isNotBlank(emBProduct.getSearchWhere())) {
            // 除去特殊字符

            emBProduct.setSearchWhere(ZcStringUtil.trim(emBProduct.getSearchWhere()));
            // emBProduct.setSearchWhere(emBProduct.getSearchWhere().replace("/'", "").replace("'", "").replace("(",
            // "").replace(" ",
            // "").replace(")",
            // "").replace(".",
            // ""));

            if (true) return;
            String isLaterOrNumber = "[0-9a-zA-Z]*";
            Pattern p1 = Pattern.compile(isLaterOrNumber);
            Matcher m1 = p1.matcher(emBProduct.getSearchWhere());

            if (ZcStringUtil.isLetters(emBProduct.getSearchWhere())) {
                emBProduct.setSpell(emBProduct.getSearchWhere().toUpperCase());

            } else {
                String regEx = "[A-Z]{0,1}[0-9]{1,10}[\\-]{0,1}[0-9]{0,3}";// 格式2022222-12
                Pattern p = Pattern.compile(regEx);
                Matcher m = p.matcher(emBProduct.getSearchWhere());
                if (m.matches()) {
                    // logger.info("纯编码");
                    emBProduct.setProductCode(emBProduct.getSearchWhere());
                } else if (m1.matches()) {
                    // logger.info("数字 +字母");
                    emBProduct.setProductCode(emBProduct.getSearchWhere());
                } else {
                    emBProduct.setProductNameOrProducingName(emBProduct.getSearchWhere());
                }
            }

        }
    }

    @Override
    public Result searchAllProductDetail(EmBProduct emBProduct) throws BaseException {
        Result ret = new Result();
        try {
            if (StringUtils.isBlank(emBProduct.getProductCode()) && null == emBProduct.getProductId()) {
                ret.setCodeResult(Result.CODE_100, "商品编号 或ID不能为空!");
                return ret;
            }
            EmBProductPrice price=new EmBProductPrice();
            price.setProductCode(emBProduct.getProductCode());
            List<EmBProductPrice> prices=emBProductPriceDao.searchEmBProductPriceList(price);
            EmBProduct product=productDao.searchAllProductDetail(emBProduct);
            for(EmBProductPrice p:prices){
                if(p.getBuyerCategory()==0){
                    product.setTenSalePrice(p.getSalePrice());
                }else if(p.getBuyerCategory()==1){
                    product.setChnSalePrice(p.getSalePrice());
                }else if(p.getBuyerCategory()==2){
                    product.setTrfSalePrice(p.getSalePrice());
                }
            }
            ret.putData("productDetail",product);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            ret.setCodeResult(Result.CODE_100, e.getMessage());
        }
        return ret;
    }

    @Override
    public void saveOrUpdateProductIntrduction(EmBProductIntroduction emBProductIntroduction) throws BaseException {
        try {

            if (StringUtils.isBlank(emBProductIntroduction.getProductCode())) {
                // add
                emBProductIntroductionDAO.insertEmBProductIntroduction(emBProductIntroduction);
            } else {
                // update
                EmBProductIntroduction isexist = emBProductIntroductionDAO.showEmBProductIntroductionDetail(emBProductIntroduction.getProductCode());
                if (null == isexist) {
                    emBProductIntroductionDAO.insertEmBProductIntroduction(emBProductIntroduction);
                } else {
                    emBProductIntroductionDAO.updateEmBProductIntroduction(emBProductIntroduction);
                }

            }
        } catch (BaseException e) {
            logger.error(e.getMessage(), e);
            throw new BaseException("保存商品说明书失败！");
        }

    }

    @Override
    public EmBProductIntroduction showEmBProductIntroductionDetail(String productCode) throws BaseException {
        return emBProductIntroductionDAO.showEmBProductIntroductionDetail(productCode);
    }

    @Override
    public Result saveOrUpdateEmBProduct(EmBProduct emBProduct) throws BaseException {
        Result ret = checkInputEmBProduct(emBProduct);
        if (ret.getCode().equals(Result.CODE_100)) {
            return ret;
        }
        if (null == emBProduct.getProductId()) {
            // insert
            // check 是否存在
            EmBProduct checkEmB = new EmBProduct();
            checkEmB.setProductCode(emBProduct.getProductCode());

            EmBProduct isExist = productDao.searchAllProductDetail(emBProduct);
            if (null != isExist) {
                ret.setCodeResult(Result.CODE_100, "主键商品编号已被商品'" + isExist.getProductName() + "'使用,请换个编号");
                return ret;
            }
            emBProduct.setUpdateDate(new Date());
            try {
                emBProduct.setCreateDate(new Date());
                productDao.insertEmBProduct(emBProduct);
                dbLog.info("INSERT-->EM_B_PRODUCT-商品编码：" + emBProduct.getProductCode() + "各字段值：" + JSON.toJSONString(emBProduct));
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
                throw new BaseException("新增商品【SQL】异常！");
            }
        } else {
            // update
            try {

                if (ZcStringUtil.isNotBlank(emBProduct.getProductTypeCode())) {
                    EmBProductType key = new EmBProductType();
                    key.setProductTypeCode(emBProduct.getProductTypeCode());
                    key = emBProductTypeDAO.showEmBProductTypeDetail(key);

                    emBProduct.setProductTypeName(key.getProductTypeName());
                }
                if (ZcStringUtil.isNotBlank(emBProduct.getSpell())) {
                    emBProduct.setSpell(emBProduct.getSpell().toUpperCase());
                }
                productDao.updateEmBProduct(emBProduct);
                dbLog.info("UPDATE-->EM_B_PRODUCT-商品编码：" + emBProduct.getProductCode() + "  各字段值：" + JSON.toJSONString(emBProduct));
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
                throw new BaseException("修改商品【SQL】异常！");
            }
        }

        //更新终端、连锁、调拨价
        // updateProductPrice(emBProduct);
        return ret;
    }

    /**
     * 更新终端、连锁、调拨价
     * @param emBProduct
     */
    private void updateProductPrice(EmBProduct emBProduct){
        try {
            EmBProductPrice price=new EmBProductPrice();
            price.setProductCode(emBProduct.getProductCode());

            price.setBuyerCategory(0);//终端价
            if(emBProduct.getTenSalePrice()!=null){
                price.setSalePrice(emBProduct.getTenSalePrice());
                updateOrInsert(price);
            }else{
                emBProductPriceDao.deleteEmBProductPrice(price);
            }

            price.setBuyerCategory(1);//连锁价
            if(emBProduct.getChnSalePrice()!=null){
                price.setSalePrice(emBProduct.getChnSalePrice());
                updateOrInsert(price);
            }else{
                emBProductPriceDao.deleteEmBProductPrice(price);
            }

            price.setBuyerCategory(2);//调拨价
            if(emBProduct.getTrfSalePrice()!=null){
                price.setSalePrice(emBProduct.getTrfSalePrice());
                updateOrInsert(price);
            }else{
                emBProductPriceDao.deleteEmBProductPrice(price);
            }

        }catch(Exception e){
            logger.error(e.getMessage(), e);
            throw new BaseException("修改终端、连锁、调拨价异常！");
        }
    }

    private void updateOrInsert(EmBProductPrice price){
        EmBProductPrice temp_price;
        temp_price=emBProductPriceDao.searchEmBProductPrice(price);
        if(temp_price!=null){
            emBProductPriceDao.updateEmBProductPrice(price);
        }else{
            emBProductPriceDao.insertEmBProductPrice(price);
        }
    }

    // 传入参数验证
    private Result checkInputEmBProduct(EmBProduct emBProduct) {
        Result ret = new Result();

        if (StringUtils.isBlank(emBProduct.getProductCode())) {
            ret.setCodeResult(Result.CODE_100, "主键 商品编号不能为空!");
        }
        if (StringUtils.isBlank(emBProduct.getProductName())) {
            ret.setCodeResult(Result.CODE_100, "商品名称不能为空!");
        }
        return ret;
    }

    @Transactional
    @Override
    public Result deleteBatchEmBProduct(EmBProduct emBProduct) throws BaseException {
        Result ret = new Result();
        if (CollectionUtils.isEmpty(emBProduct.getList())) {
            ret.setCodeResult(Result.CODE_100, "未选择任何要删除的商品");
            return ret;
        }
        for (EmBProduct b : emBProduct.getList()) {
            try {
                productDao.deleteEmBProduct(b);
                dbLog.info("DELETE-->EM_B_PRODUCT-商品编码：" + b.getProductCode());
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
                throw new BaseException("商品编号：" + b.getProductCode() + " 删除失败,找到跟这个商品相关的子记录。");
            }
        }
        return ret;

    }

    @Override
    public void deleteEmBProduct(EmBProduct emBProduct) throws BaseException {
        // TODO Auto-generated method stub

    }

    @Transactional
    @Override
    public Result batchUpdateEmBProduct(EmBProduct emBProduct) throws BaseException {
        Result ret = new Result();
        if (CollectionUtils.isEmpty(emBProduct.getList())) {
            ret.setCodeResult(Result.CODE_100, "请选择要操作的行!");
            return ret;
        }
        try {
            for (EmBProduct e : emBProduct.getList()) {
                e.setUpdateDate(new Date());
                productDao.updateEmBProduct(e);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new BaseException("更新商品数据失败");
        }
        return ret;
    }

    @Override
    public Result searchSimpleProductList(EmBProduct emBProduct) throws BaseException {
        Result ret = new Result();
        if (emBProduct.getLimitRow() == 0) {
            ret.setCodeResult(Result.CODE_100, "缺少行数限制 条件！");
            return ret;
        }
        try {
            List<EmBProduct> l = productDao.searchSimpleProductList(emBProduct);
            ret.setRows(l);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new BaseException("获取商品列表异常 请联系管理员!");
        }
        return ret;
    }

    @Override
    public Result searchManagerProductList(EmBProduct emBProduct, Page<EmBProduct> page) throws BaseException {
        Result result = new Result();
        try {
            checkSearchType(emBProduct);

            result.setResultPage(productDao.searchPageProduct(emBProduct, page));
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new BaseException(Result.CODE_100, "查询商品列表异常");
        }
        return result;

    }

}
